# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: client_interface.py
Author: kij
Create Date: 2021/3/2
-------------------------------------------------
"""
import os
import json
from client import MyClient
from conn import setting


def put_file(app_client, *args):
	return json.loads(app_client.update_file(args[0][0]).decode('utf-8'))


def get_file(app_client, *args):
	# 文件名称和路径信息
	return app_client.download_file(args[0][0])

def re_get_file(app_client, re_get_file_dict):
	# 断点续传 文件
	return app_client.re_get_file(re_get_file_dict)


def ls_file(app_client, *args):
	return json.loads(app_client.ls_file().decode('utf-8'))


def dir_file(app_client, *args):
	response = json.loads(app_client.dir_file().decode('utf-8'))

	if response.get('code') == 200:
		print("dir命令===", response['data'])
	else:
		print("dir命令===", response['msg'])


def cd_file(app_client, *args):
	path_dict = {
		'file_path': args[0][0],
	}
	return app_client.cd_file(path_dict)


def mkdir_file(app_client, *args):
	path_dict = {
		'file_path': args[0][0],
	}
	return json.loads(app_client.mkdir_file(path_dict).decode('utf-8'))


func_dict = {
	'put': put_file,  # 上传下载和显示文件创建文件夹
	'get': get_file,
	'ls': ls_file,
	'cd': cd_file,
	'dir': dir_file,
	'mkdir': mkdir_file,
}


# 校验参数是否正确
def argv_verification(ip='127.0.0.1', port=9997):
	"""验证参数并链接"""
	my_client = MyClient(ip, port)
	result = my_client.request.get_msg()
	if not result:
		return False, '断开链接'
	if json.loads(result.decode('utf-8')).get('code') == 200:
		return True, my_client
	else:
		return False, '链接失败再次尝试'


def close_net(app_client):
	app_client.close_net()
	return True


def auth(app_client, user_name, user_password):
	user_dict = {
		'username': user_name,
		'password': user_password
	}
	result = app_client.auth(user_dict)
	if not result:
		return app_client, app_client.request.close()
	return app_client, json.loads(result.decode('utf-8'))


def switch_func(input_msg, app_client):
	input_list = str(input_msg).split(" ", maxsplit=1)
	if input_list[0] not in func_dict:
		result_dict = {'msg': '输入错误'}
		return result_dict
	else:
		return func_dict.get(input_list[0])(app_client, input_list[1:], )
